//日期格式化
export function formatDate(date, fmt) {
  if (('' + date).length === 0 || !date) {
    return null
  }
  if (('' + date).length === 8) {
    date = formatDateString(date)
  }
  if (typeof date !== 'object') {
    date = new Date(date)
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftzero(str))
    }
  }
  return fmt
}
//yyyyMMdd转yyyy-MM-dd
export function formatDateString(dateString) {
  var pattern = /(\d{4})(\d{2})(\d{2})/
  if (dateString.length == 8) {
    var formatedDate = dateString.replace(pattern, '$1-$2-$3')
    return formatedDate
  } else {
    return dateString
  }
}
//hhmmss转hh:mm:ss || hhmm转hh:mm
export function formatTimeString(timeString) {
  if (timeString.length == 6) {
    var pattern = /(\d{2})(\d{2})(\d{2})/
    var formatedTime = timeString.replace(pattern, '$1:$2')
    return formatedTime
  } else if (timeString.length == 4) {
    var pattern = /(\d{2})(\d{2})/
    var formatedTime = timeString.replace(pattern, '$1:$2')
    return formatedTime
  } else {
    return timeString
  }
}
//hh:mm:ss转date
export function timeStringToDate(timeString, dateString = formatDate(new Date(), 'yyyy-MM-dd')) {
  if (!timeString) {
    return null
  }
  if (timeString.length === 6) {
    timeString = formatTimeString(timeString)
  }
  var time = dateString + ' ' + timeString
  time = time.replace(/-/g, ':').replace(' ', ':')
  time = time.split(':')
  var date = new Date(time[0], time[1] - 1, time[2], time[3], time[4], time[5])
  console.log('date', date)
  //var date = new Date(dateString + " " + timeString);
  return date
}
//日期转date
export function dateStringToDate(dateString) {
  if (!dateString) {
    return null
  }
  if (dateString.length === 8) {
    dateString = formatDateString(dateString)
  }
  var date = new Date(dateString)
  return date
}

function padLeftzero(str) {
  return ('00' + str).substr(str.length)
}
// 日期格式化
export const dateFormat = (fmt, date) => {
  let ret
  if (dateString.length === 8) {
    dateString = formatDateString(date)
  }
  const opt = {
    'y+': dateString.getFullYear().toString(), // 年
    'M+': (dateString.getMonth() + 1).toString(), // 月
    'd+': dateString.getDate().toString(), // 日
    'H+': dateString.getHours().toString(), // 时
    'm+': dateString.getMinutes().toString(), // 分
    's+': dateString.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  }
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
    }
  }
  return fmt
}